package com.alien.admin.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description: redis实现的分布式锁
 * @Author: zsy
 * @Date: 2021/10/29 9:29
 */
@Component
public class RedisLockUtil {

    /** 获取锁的超时时间 */
    private static final long timeout = 300;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 尝试获取锁
     * @param key
     * @param expiredTime
     * @return
     */
    public boolean tryLock(String key, Long expiredTime) {
        String requestId = UUID.randomUUID().toString();
        return redisTemplate.opsForValue().setIfAbsent(key, requestId, expiredTime, TimeUnit.SECONDS);
    }

    /**
     * 锁定，会等待
     * @param key
     * @param expiredTime
     * @return
     */
    public boolean lock(String key, Long expiredTime) {
        String requestId = UUID.randomUUID().toString();
        Long start = System.currentTimeMillis();

        for(;;) {
            Boolean ret = redisTemplate.opsForValue().setIfAbsent(key, requestId, expiredTime, TimeUnit.SECONDS);
            if(ret) {
                return true;
            }

            // 超时时间内，进行等待
            long end = System.currentTimeMillis() - start;
            if(end >= timeout) {
                return false;
            }
        }
    }

    /**
     * 解锁，可传入多个值
     * @param key
     */
    public void unlock(String... key) {
        if(key != null && key.length > 0){
            if(key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }
}
